//
//  Ext+Date.swift
//  Schedule
//
//  Created by zhaojunming on 2024/10/24.
//

import Foundation

extension Date {
    static var tsp: String {
        let now = Date()
        let timestamp = now.timeIntervalSince1970
        let timestampInSeconds = Int(timestamp)
        return String(timestampInSeconds)
    }
    
    func tspFormat(_ format: String = "yyyy-MM-dd HH:mm:ss") -> String {
        let dfmatter = DateFormatter()
        dfmatter.dateFormat = format
        dfmatter.timeZone = TimeZone.current
        return dfmatter.string(from: self)
    }
}

extension String {
    func tspFormat(_ format: String = "yyyy-MM-dd HH:mm:ss") -> String {
        // 1. 字符串转 Double（秒级时间戳需用 Double 存储，避免精度丢失）
        guard let seconds = Double(self) else {
            print("错误：时间戳字符串非数字（\(self)）")
            return "--"
        }
        
        // 2. 校验长度（10位秒级，允许前后无空格）
        guard self.trimmingCharacters(in: .whitespacesAndNewlines).count == 10 else {
            print("错误：秒级时间戳字符串需10位（\(self)）")
            return "--"
        }
        
        // 3. 转 Date 并格式化（同之前逻辑）
        let date = Date(timeIntervalSince1970: seconds)
        let dfmatter = DateFormatter()
        dfmatter.dateFormat = format
        dfmatter.timeZone = TimeZone.current
        return dfmatter.string(from: date)
    }
}
